package com.wms.ymcc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wms.ymcc.UserIdApi;
import com.wms.ymcc.api.ESCourseAPI;
import com.wms.ymcc.api.MediaFileAPI;
import com.wms.ymcc.constant.ValidationConstants;
import com.wms.ymcc.doc.CourseDoc;
import com.wms.ymcc.domain.*;
import com.wms.ymcc.dto.*;
import com.wms.ymcc.exception.GlobalBaseException;
import com.wms.ymcc.mapper.*;
import com.wms.ymcc.result.JSONResult;
import com.wms.ymcc.service.ICourseChapterService;
import com.wms.ymcc.service.ICourseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wms.ymcc.service.ICourseTeacherService;
import com.wms.ymcc.utils.utils.LoginContext;
import com.wms.ymcc.vo.CourseDetailVo;
import com.wms.ymcc.vo.CourseInfoResultVo;
import com.wms.ymcc.vo.CourseInfoVo;
import lombok.extern.slf4j.Slf4j;
//import org.apache.rocketmq.client.producer.SendResult;
//import org.apache.rocketmq.spring.core.RocketMQTemplate;
//import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.messaging.support.MessageBuilder;
//import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 阿盛哟
 * @since 2025-06-01
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseResourceMapper courseResourceMapper;

    @Autowired
    private ICourseTeacherService courseTeacherService;


    @Autowired
    private CourseSummaryMapper courseSummaryMapper;

    @Autowired
    private ESCourseAPI esCourseAPI;

//    @Autowired
//    private RocketMQTemplate rocketMQTemplate;

     //章节
    @Autowired
    private ICourseChapterService courseChapterService;

    @Autowired
    private MediaFileAPI mediaFileAPI;


    @Autowired
    private UserIdApi userIdApi;

    /**
     * 新增课程
     * @param addCourseDto
     *
     */
    @Override
    public void save(AddCourseDto addCourseDto) {

        Course course = addCourseDto.getCourse();
        CourseDetail courseDetail = addCourseDto.getCourseDetail();
        CourseMarket courseMarket = addCourseDto.getCourseMarket();
        CourseResource courseResource = addCourseDto.getCourseResource();
        List<Long> teacherIds = addCourseDto.getTeacherIds();

        // 1. 校验， 略

        // 2. 添加五张表
        // t_course
        course.setStatus(Course.OFFLINE_STATUS);
        // 获取LoginId,
        Login login = LoginContext.getLogin();
        course.setLoginId(login.getId());
        course.setLoginUserName(login.getUsername());
        course.setTotalMinute(0);
        // teacherIds ---》 tname
        List<Teacher> teachers = teacherMapper.selectBatchIds(teacherIds);
        StringBuilder sb = new StringBuilder();
        for (Teacher teacher : teachers) {
            sb.append(teacher.getName()).append(",");
        }
        course.setTeacherNames(sb.toString());
        course.setChapterCount(0);
        insert(course);

        // t_course_detail
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);

        // t_course_market
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);

        // t_course_resource
        courseResource.setCourseId(course.getId());
        courseResourceMapper.insert(courseResource);

        // t_course_teacher
        ArrayList<CourseTeacher> courseTeachers = new ArrayList<>();

        for (Long teacherId : teacherIds) {
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(teacherId);
            courseTeachers.add(courseTeacher);
        }
        courseTeacherService.insertBatch(courseTeachers);
    }


    /**
     * 上线课程
     * @param id
     */
    @Transactional
    @Override
    public void onLineCourse(Long id) {
        // 1. 非空校验
        if  (id == null) {
            throw new GlobalBaseException("非法请求");
        }

        // 2. 查询课程信息
        Wrapper<Course> ww = new EntityWrapper<>();
        ww.eq("id",id);
        Course course = selectOne(ww);

        // 3. 校验课程状态
        if(course.getStatus()==Course.ONLINE_STATUS){
            throw new GlobalBaseException("课程已上线");
        }

        // 4. 修改课程状态  1. 上线
        course.setStatus(Course.ONLINE_STATUS);
        course.setOnlineTime(new Date());
        updateById(course);

        // 5. 课程上线,准备CourseDoc对象
        CourseDoc courseDoc = new CourseDoc();
        BeanUtils.copyProperties(course,courseDoc);

        // 收费免费。。。
        CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseMarket,courseDoc);

        // 收费
        courseDoc.setCharge(courseMarket.getCharge()==1?"收费":"免费");

        // 课程简介
        CourseSummary courseSummary = courseSummaryMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseSummary,courseDoc);


        // 6. 远程调用Search服务
        JSONResult jsonResult = esCourseAPI.save(courseDoc);// 调用Search服务失败[401] during [POST] to [http://service-search/esCourse/save] [ESCourseAPI#save(CourseDoc)]: []
        if(!jsonResult.isSuccess()){
            throw new GlobalBaseException("存入ES失败");
        }

        // 7. 广告， 推送消息 ,异步， 发送消息  邮件
        /**
         * 1. 邮件
         * 2. 手机短信
         * 3. 站内推送
         *  异步推送  MQ, 同步消息， 异步消息，
         */
//        publish(course);
       /* new Thread(()->{  // 线程池
            publish(course);  // 单启一个线程
        });*/
    }

    /**
     *  课程详情, 包含课程信息，课程营销信息，课程章节信息，课程id对应的视频
     * @param courseId
     */
    @Override
    public CourseDetailVo detail(Long courseId) {
        if(courseId==null){
            throw new GlobalBaseException("非法请求");
        }

        CourseDetailVo detailVo = new CourseDetailVo();
        // 课程信息
//        private Course course;
        Course course = selectById(courseId);
        detailVo.setCourse(course);

        // 课程营销信息
//        private CourseMarket courseMarket;
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        detailVo.setCourseMarket(courseMarket);
        // 课程章节信息
//        private List<CourseChapter> courseChapters;
        List<CourseChapter> courseChapters = courseChapterService.listByCourseId(courseId);

        // 课程id对应的视频
        JSONResult jsonResult = mediaFileAPI.findByCourseId(courseId);
        String jsonStr = jsonResult.getData().toString();
        List<MediaFile> mediaFiles = JSONObject.parseArray(jsonStr, MediaFile.class);

        // 为什么空指针呢
        mediaFiles.forEach(mediaFile -> {
            courseChapters.forEach(courseChapter -> {
                if(mediaFile.getChapterId().longValue() == courseChapter.getId().longValue()){
                    courseChapter.getMediaFiles().add(mediaFile);
                }
            });
        });

        detailVo.setCourseChapters(courseChapters);

        // 课程讲师信息
//        private List<Teacher> teachers;
        List<Teacher> teachers = courseTeacherService.queryTeachersByCourseId(courseId);
        detailVo.setTeachers(teachers);
        //  课程详情信息
//        private Course courseDetail;
        CourseDetail courseDetail = courseDetailMapper.selectById(courseId);
        detailVo.setCourseDetail(courseDetail);
        // 课程概述信息
//        private Course courseSummary;
        CourseSummary courseSummary = courseSummaryMapper.selectById(courseId);
        detailVo.setCourseSummary(courseSummary);
        return detailVo;
    }

    /**
     * 课程购买的信息查询
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoResultVo courseInfo(String courseId) {
        if(StringUtils.isEmpty(courseId)){
            throw new GlobalBaseException("非法请求");
        }
        // t_course 对传入的courseId进行切割，获取所有课程id
        String[] courseIds = courseId.split(",");
        List<Course> courses = selectBatchIds(Arrays.asList(courseIds));
        List<CourseMarket> courseMarkets = courseMarketMapper.selectBatchIds(Arrays.asList(courseIds));

        List<CourseInfoVo> courseInfoVos = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for ( CourseMarket courseMarket : courseMarkets) {
            totalAmount = totalAmount.add(courseMarket.getPrice());
            for (Course cours : courses) {
                if(cours.getId().longValue()==courseMarket.getId().longValue()){
                    CourseInfoVo courseInfoVo = new CourseInfoVo(cours, courseMarket);
                    courseInfoVos.add(courseInfoVo);
                }
            }
        }

        CourseInfoResultVo courseInfoResultVo = new CourseInfoResultVo();
        courseInfoResultVo.setCourseInfos(courseInfoVos);
        courseInfoResultVo.setTotalAmount(totalAmount);
        return courseInfoResultVo;
    }

    /**
     * 远程调用的课程购买信息
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoResultVo courseInfoApi(List<Long> courseId) {
        // t_course
        List<Course> courses = selectBatchIds(courseId);
        List<CourseMarket> courseMarkets = courseMarketMapper.selectBatchIds(courseId);

        List<CourseInfoVo> courseInfoVos = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for ( CourseMarket courseMarket : courseMarkets) {
            totalAmount = totalAmount.add(courseMarket.getPrice());
            for (Course cours : courses) {
                if(cours.getId().longValue()==courseMarket.getId().longValue()){
                    CourseInfoVo courseInfoVo = new CourseInfoVo(cours, courseMarket);
                    courseInfoVos.add(courseInfoVo);
                }
            }
        }

        CourseInfoResultVo courseInfoResultVo = new CourseInfoResultVo();
        courseInfoResultVo.setCourseInfos(courseInfoVos);
        courseInfoResultVo.setTotalAmount(totalAmount);
        return courseInfoResultVo;
    }


    //MQ发送消息
//    public void publish(Course course){
//
//        // 调用MQ,站内推送
//
//        // @TODO  查询所有的用户id，把用户id放入list中 （已完成）
//         JSONResult jsonResult =userIdApi.list();
//
//        List<Map<String, Object>> users = (List<Map<String, Object>>) jsonResult.getData();
//         List<Long> ids = users.stream().map(
//                 user -> ((Integer) user.get("id")).longValue()
//         ).collect(Collectors.toList());  //从数据库获取的id集合
//
//
//        List<Long> ids = Arrays.asList(1l, 2l, 3l, 4l, 5l);
//
//        MessageStationDto messageStationDto = new MessageStationDto();
//        messageStationDto.setTitle(course.getName());
//        messageStationDto.setContent("新课mq视频，很好");
//        messageStationDto.setType("系统消息");
//        messageStationDto.setIds(ids);
//
//        SendResult stationResult = rocketMQTemplate.syncSend(
//                ValidationConstants.ROCKETMQ_TOPIC_PUBLISH+":"+ValidationConstants.ROCKETMQ_TAGS_STATION,
//                MessageBuilder.withPayload(JSONObject.toJSONString(messageStationDto)).build());
//
//        // 发送成功和失败的结果。
//        //System.out.println("发送站内消息结果："+result);
//        log.info("发送站内消息结果：{}",stationResult);
//        // 调用MQ,手机短信
//        // @TODO   查询出用户和用户手机号对应的所有数据 略(已完成)


    //    List<User2PhoneDto> list = users.stream().map(
    //            user -> new User2PhoneDto(
    //                    ((Integer) user.get("id")).longValue(),
    //                    (String) user.get("phone")
    //            )
    //    ).collect(Collectors.toList());



//        List<User2PhoneDto> list = Arrays.asList(
//                new User2PhoneDto(1l,"13888888881"),
//                new User2PhoneDto(2l,"13888888882"),
//                new User2PhoneDto(3l,"13888888883"),
//                new User2PhoneDto(4l,"13888888884"),
//                new User2PhoneDto(5l,"13888888885")
//        );
//
//        MessageSmsDto  messageSmsDto = new MessageSmsDto();
//        messageSmsDto.setTitle(course.getName());
//        messageSmsDto.setContent("新课mq视频，很好");
//        messageSmsDto.setUser2PhoneDtos(list);
//        SendResult smsResult = rocketMQTemplate.syncSend(
//                ValidationConstants.ROCKETMQ_TOPIC_PUBLISH+":"+ValidationConstants.ROCKETMQ_TAGS_SMS,
//                MessageBuilder.withPayload(JSONObject.toJSONString(messageSmsDto)).build());
//
//        log.info("短信推送消息结果：{}",messageSmsDto);
//
//        // 调用MQ,邮件推送
//        List<User2EmailDto> list1 = Arrays.asList(
//                new User2EmailDto(1l,"13888888881@qq.com"),
//                new User2EmailDto(2l,"13888888882@qq.com"),
//                new User2EmailDto(3l,"13888888883@qq.com"),
//                new User2EmailDto(4l,"13888888884@qq.com"),
//                new User2EmailDto(5l,"13888888885@qq.com")
//        );
//        MessageEmailDto messageEmailDto = new MessageEmailDto();
//        messageEmailDto.setTitle(course.getName());
//        messageEmailDto.setContent("新课mq视频，很好");
//        messageEmailDto.setUser2EmailDtos(list1);
//
//        SendResult emailResult = rocketMQTemplate.syncSend(
//                ValidationConstants.ROCKETMQ_TOPIC_PUBLISH+":"+ValidationConstants.ROCKETMQ_TAGS_EMAIL,
//                MessageBuilder.withPayload(JSONObject.toJSONString(messageEmailDto)).build());
//
//        log.info("邮件推送消息结果：{}",emailResult);
//
//    }

}
